<template>
  <div class="data-panel">
    <div class="data-item" @mousedown="downloadXml()" title="下载XML格式数据">
      <div class="data-item-icon bpmn-xml"></div>
    </div>
    <div class="data-item" @mousedown="uploadImage()" title="上传图片到服务器">
      <div class="data-item-icon bpmn-img"></div>
    </div>
    <div class="data-item">
      <input type="file" className="data-upload" @change="uploadXml($event)" title="上传XML格式数据"/>
      <div class="data-item-icon bpmn-upload"></div>
    </div>
    <div class="data-item" @mousedown="getGraphRawData()" title="下载JSON格式数据" >
      <div class="data-item-icon bpmn-look"></div>
    </div>
  </div>
</template>
<script lang="ts">
import LogicFlow from '@logicflow/core';

function download(filename: string, text: string) {
  var element = document.createElement("a");
  element.setAttribute(
    "href",
    "data:text/plain;charset=utf-8," + encodeURIComponent(text)
  );
  element.setAttribute("download", filename);
  element.style.display = "none";
  document.body.appendChild(element);
  element.click();
  document.body.removeChild(element);
}

function isJSON(str:string) {
  if (typeof str == "string") {
    try {
      var obj = JSON.parse(str);
      if (typeof obj == "object" && obj) {
        return true;
      } else {
        return false;
      }
    } catch (e) {
      // console.log("error：" + str + "!!!" + e);
      return false;
    }
  }
  // console.log("It is not a string!");
}

type FileEventTarget = EventTarget & { files: FileList };

export default {
  name: "BpmnDataPanel",
  data() {
    return {};
  },
  props: {
    lf: Object,
  },

  mounted() {},

  methods: {
    downloadXml() {
      const data = (this.$props.lf as LogicFlow).getGraphData() as string;
      download("logic-flow.xml", data);
    },
    async uploadImage() {
      try {
        // console.log('🔄 开始生成流程图截图并上传...');
        
        const lf = this.$props.lf as LogicFlow;
        
        // 使用原生方法创建canvas截图，避免LogicFlow的getSnapshot方法
        try {
          // 获取LogicFlow的容器元素
          const container = lf.container;
          
          // console.log('📷 使用原生方法生成截图...');
          
          // 创建canvas
          const canvas = document.createElement('canvas');
          const ctx = canvas.getContext('2d');
          
          if (!ctx) {
            throw new Error('无法创建canvas上下文');
          }
          
          // 获取容器尺寸
          const rect = container.getBoundingClientRect();
          canvas.width = rect.width;
          canvas.height = rect.height;
          
          // 填充白色背景
          ctx.fillStyle = '#ffffff';
          ctx.fillRect(0, 0, canvas.width, canvas.height);
          
          // 查找LogicFlow的SVG元素
          const svgElement = container.querySelector('svg');
          if (svgElement) {
            // 将SVG转换为图片
            const svgData = new XMLSerializer().serializeToString(svgElement);
            const img = new Image();
            
            img.onload = async () => {
              // 绘制到canvas
              ctx.drawImage(img, 0, 0);
              
              // console.log('📷 原生截图生成成功，开始上传...');
              
              // 将截图转换为Blob并上传
              canvas.toBlob(async (blob: Blob | null) => {
                if (!blob) {
                  // console.error('无法生成图片');
                  return;
                }
                
                await this.doUpload(blob);
              }, 'image/png');
            };
            
            img.onerror = () => {
              // console.error('SVG转换为图片失败');
              if ((window as any).ElMessage) {
                (window as any).ElMessage.error('截图生成失败，请重试');
              }
            };
            
            // 设置SVG数据
            const svgBlob = new Blob([svgData], { type: 'image/svg+xml;charset=utf-8' });
            const url = URL.createObjectURL(svgBlob);
            img.src = url;
            
          } else {
            throw new Error('未找到SVG元素');
          }
          
        } catch (error) {
          // console.error('原生截图失败:', error);
          
          // 显示错误信息
          if ((window as any).ElMessage) {
            (window as any).ElMessage.error('截图生成失败，请重试');
          }
        }
        
      } catch (error) {
        // console.error('❌ 截图生成失败:', error);
        if ((window as any).ElMessage) {
          (window as any).ElMessage.error('截图生成失败');
        }
      }
    },
    
    // 提取上传逻辑为单独方法
    async doUpload(blob: Blob) {
      // console.log('📤 开始上传图片...');
      
      // 创建FormData上传图片
      const formData = new FormData();
      formData.append('file', blob, 'flowchart.png');
      
      try {
        // 使用项目的axios实例上传图片
        const axios = (await import('axios')).default;
        
        // 获取token
        const token = localStorage.getItem('token') || '';
        
        // 使用项目的APIs实例，避免硬编码URL
        const { APIs } = (await import('@/Http/http'));
        const response = await APIs.post('/api/Write/FileWiter', formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
            'Authorization': `Bearer ${token}`
          }
        });
        
        if (response.data) {
          const imageUrl = response.data;
          // console.log('✅ 图片上传成功，地址:', imageUrl);
          
          // 将图片地址存储到全局变量，供保存方法使用
          (window as any).flowImageUrl = imageUrl;
          
          // console.log('图片地址已存储到 window.flowImageUrl:', imageUrl);
          
          // 显示成功提示
          if ((window as any).ElMessage) {
            (window as any).ElMessage.success('图片上传成功！');
          }
        } else {
          // console.error('❌ 图片上传失败: 无响应数据');
          if ((window as any).ElMessage) {
            (window as any).ElMessage.error('图片上传失败');
          }
        }
      } catch (error) {
        // console.error('❌ 上传请求失败:', error);
        if ((window as any).ElMessage) {
          (window as any).ElMessage.error('图片上传失败');
        }
      }
    },
    uploadXml(ev: Event) {
      const file = (ev.target as FileEventTarget).files[0];
      const reader = new FileReader();
      reader.onload = (event: ProgressEvent<FileReader>) => {
        if (event.target) {
          let data = event.target.result as string;
          /* 这里JSON无法解析，只有XML可以载入？？
          if (isJSON(data)) {
            data = JSON.parse(data);
          }
          */
          (this.$props.lf as LogicFlow).render(data as any);
        }
      };
      reader.readAsText(file); // you could also read images and other binaries
    },
    getGraphRawData() {
      const data = JSON.stringify((this.$props.lf as LogicFlow).getGraphRawData());
      //download("logic-flow.txt", data);
      // console.log(data);
    //  var jsonData = JSON.parse(data);
    //  APIs.post('/api/WorkFlow/CreateWorkFlow',jsonData).then(res=>{
    //     // console.log(res.data);
    //  })
    },
  },
};
</script>
<style>
.data-panel {
  position: absolute;
  bottom: 10px;
  left: 10px;
  height: 20px;
  width: auto;
  padding: 10px;
  background-color: white;
  box-shadow: 0 0 10px 1px rgb(228, 224, 219);
  border-radius: 6px;
  text-align: center;
  z-index: 101;
}
.data-item {
  margin: 0px 5px;
  display: inline-block;
  position: relative;
}
.data-item-icon {
  width: 20px;
  height: 20px;
  background-size: cover;
}
.data-label {
  font-size: 12px;
  margin-top: 5px;
  user-select: none;
}

.data-upload {
  opacity: 0;
  position: absolute;
  width: 20px;
  height: 20px;
  left: 0;
  right: 0;
}

.bpmn-xml {
  background: url()
    center center no-repeat;
  cursor: grab;
}

.bpmn-img {
  background: url()
    center center no-repeat;
  cursor: grab;
}

.bpmn-upload {
  background: url()
    center center no-repeat;
  cursor: grab;
}

.bpmn-look {
  background: url()
    center center no-repeat;
  cursor: grab;
}
</style>
